package com.liufei.dao;

import com.liufei.util.DatabaseUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiuFei
 * @create 2017-12-25 11:29
 */
public class DatabaseReader {

    private Connection connection;

    public DatabaseReader()  {
        connection = DatabaseUtils.getConnection();
    }

    public Connection getConnection() {
        return connection;
    }

    /**
     * 获取数据库中的所有表
     *
     * @param databaseName 数据库名
     * @return
     * @throws SQLException
     */
    public List<Map<String, String>> getTables(String databaseName) throws SQLException {
        DatabaseMetaData dbmd = connection.getMetaData();
        String[] types = {"TABLE"};
        ResultSet resultSet = dbmd.getTables(null, databaseName, "sys_%", types);

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        while(resultSet.next()) {
            Map<String, String> map = new LinkedHashMap<String, String>();
            map.put("TABLE_NAME", resultSet.getString("TABLE_NAME"));
            map.put("REMARKS", resultSet.getString("REMARKS"));
            list.add(map);
        }
        return list;
    }

    /**
     * 获取某个表的信息
     *
     * @param databaseName 数据库名
     * @param tableName 表名
     * @return
     * @throws SQLException
     */
    public List<Map<String, String>> getTableInfo(String databaseName, String tableName) throws SQLException {

        DatabaseMetaData dbmd = connection.getMetaData();
        ResultSet resultSet = dbmd.getColumns(null, databaseName, tableName, "%");

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        while(resultSet.next()) {
            Map<String, String> map = new LinkedHashMap<String, String>();
            map.put("REMARKS", resultSet.getString("REMARKS"));
            map.put("COLUMN_NAME", resultSet.getString("COLUMN_NAME"));
            map.put("TYPE_NAME", resultSet.getString("TYPE_NAME"));
            map.put("COLUMN_SIZE", resultSet.getString("COLUMN_SIZE"));
            map.put("COLUMN_DEF", resultSet.getString("COLUMN_DEF"));
            map.put("IS_NULLABLE", resultSet.getString("IS_NULLABLE"));
            list.add(map);
        }

        return list;
    }
}
